
enum BUTTON {
    //% block="a"
    'A',
    //% block="b"
    'B'
}

//% color="#ff8000" iconWidth=50 iconHeight=40
namespace onnx{

    
    //% block="设置识别结果类别标签名称[LIST]" blockType="command"
    //% LIST.shadow="list" LIST.defl="'class1', 'class2', 'class3', 'class4'"
    export function disImgq(parameter: any, block: any) {
        let list=parameter.LIST.code;
    
        Generator.addInitHeader('list',`class_list = ${list}`);

    }
    //% block="设置图像分辨率[NUM]" blockType="command"
    //% NUM.shadow="number" NUM.defl="224"
    export function disImgqq(parameter: any, block: any) {
        let num=parameter.NUM.code;
    
        Generator.addInitHeader('num',`inf_res = ${num}`);

    }
        //% block="分类模型" blockType="tag"
        export function noteSep111() {

        }
    //% block="导入训练好的ONNX分类模型 路径[PATH]" blockType="command"
    //% PATH.shadow="string" PATH.defl="model.onnx"
    export function saveImage(parameter: any, block: any) {
        let path=parameter.PATH.code;
        Generator.addImport(`import onnxruntime as ort\nimport numpy as np`)
        Generator.addCode(`model_path = ${path}
# Load the ONNX model
onnx_session = ort.InferenceSession(model_path)
onnx_input_name = onnx_session.get_inputs()[0].name
onnx_output_name = onnx_session.get_outputs()[0].name`)

    }
    //% block="调用ONNX分类模型识别一次图像[IMG] 存入结果" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    export function disImg(parameter: any, block: any) {
        let img=parameter.IMG.code;
        Generator.addInitHeader('num',`inf_res = 224`);
        Generator.addCode(`
# Preprocess the frame
onnx_img = cv2.resize(${img}, (inf_res, inf_res))
onnx_input_data = onnx_img.astype(np.float32) / 255.0  # Convert to float and normalize
# Add a batch dimension
onnx_input_data = np.expand_dims(onnx_input_data, axis=0)
# Run inference
onnx_output_data = onnx_session.run([onnx_output_name], {onnx_input_name: onnx_input_data})[0]
onnx_idx = np.argmax(onnx_output_data)
onnx_confidence = onnx_output_data[0][onnx_idx]
`);

    }
    //% block="从分类结果中取[CFRESULT]" blockType="reporter"
    //% CFRESULT.shadow="dropdown" CFRESULT.options="CFRESULT"
    export function getResult(parameter: any, block: any) {
        let result=parameter.CFRESULT.code;
        //console.log(result)
        if(result=="confidence"){
            Generator.addCode(`onnx_confidence`)
        }else{
            Generator.addCode(`onnx_idx`)
        }


    } 
            //% block="检测模型" blockType="tag"
            export function noteSep11() {

            }
    //% block="导入训练好的ONNX检测模型 路径[PATH]  置信度阈值[NUM] loU阈值[LU]" blockType="command"
    //% PATH.shadow="string" PATH.defl="model.onnx"

    //% NUM.shadow="number" NUM.defl="0.25"
    //% LU.shadow="number" LU.defl="0.70"
    export function saveImage1(parameter: any, block: any) {
        let path=parameter.PATH.code;
        let num=parameter.NUM.code;
        let lu=parameter.LU.code;
        Generator.addImport(`from mindplusyoloonnxlib import YOLOONNXModel`)
        Generator.addInitHeader('num',`inf_res = 224`);
        Generator.addCode(`
detection = YOLOONNXModel(${path}, class_list, inf_res,${num},${lu})
`)

    }
    


    //% block="调用ONNX检测模型识别一次图像[IMG] 存入结果" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    export function disImg1(parameter: any, block: any) {
        let img=parameter.IMG.code;
    
        Generator.addCode(`${img}, result_value , class_ids, scores_value = detection.run(${img})`);

    }
    
    //% block="从检测结果中取原始数据" blockType="reporter"
    export function getResulta(parameter: any, block: any) {
            Generator.addCode(`result_value`)
        }

    //% block="从检测结果中取目标总数" blockType="reporter"
    export function getResultab(parameter: any, block: any) {
        Generator.addCode(`len(result_value['boxes'])`)
    }

    //% block="从检测结果中取第[NUM]个框的[CFRESULT]" blockType="reporter"
    //% NUM.shadow="number" NUM.defl="0"
    //% CFRESULT.shadow="dropdown" CFRESULT.options="CFRESULT"
    export function getResultz(parameter: any, block: any) {
        let num=parameter.NUM.code;
        let result=parameter.CFRESULT.code;
        //console.log(result)
        if(result=="confidence"){
            Generator.addCode(`scores_value[${num}]`)
        }else{
            Generator.addCode(`class_ids[${num}]`)
        }


    }
    //% block="从检测结果中取第[NUM]个目标的框数据（元组）" blockType="reporter"
    //% NUM.shadow="number" NUM.defl="0"
    export function getResultc(parameter: any, block: any) {
        let num=parameter.NUM.code;
        Generator.addCode(`result_value['boxes'][${num}]`

    }
    //% block="从检测结果中取第[NUM]个目标的[BOX]" blockType="reporter"
    //% NUM.shadow="number" NUM.defl="0"
    //% BOX.shadow="dropdown" BOX.options="BOX"
    export function getResultd(parameter: any, block: any) {
        let num=parameter.NUM.code;
        let BOX=parameter.BOX.code;
        Generator.addCode(`result_value['boxes'][${num}][${BOX}]`)

    }
        //% block="图像处理" blockType="tag"

        export function noteSep1() {

        }
    

    //% block="从本地文件[FILE]获取图像 赋值给变量[IMG]" blockType="command"
    //% FILE.shadow="string" FILE.defl="img.png"
    //% IMG.shadow="normal" IMG.defl="img"
    export function readPice(parameter: any, block: any) {
        let img=parameter.IMG.code;
        let file=parameter.FILE.code;
        Generator.addImport(`import cv2\nimport sys\nimport numpy as np`)
        Generator.addImport(`import matplotlib.font_manager\nimport sys\nimport os`)
        Generator.addInit(`setwindowfull`,`if "linux" in sys.platform:
    font_path = 'HYQiHei_50S.ttf'
    cv2.namedWindow('cvwindow',cv2.WND_PROP_FULLSCREEN)
    cv2.setWindowProperty('cvwindow', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
else: 
    font_path = matplotlib.font_manager.findfont('SimHei')
`)
        Generator.addCode(`cv2.waitKey(5)\n${img} = cv2.imread(${file}, cv2.IMREAD_UNCHANGED)`)

    }
        //% block="---"
        export function noteSep4() {

        }
    
    //% block="OpenCV初始化打开摄像头直到成功 编号[CAMNUM]" blockType="command"
    //% CAMNUM.shadow="number" CAMNUM.defl="-1"
    export function readcap(parameter: any, block: any) {
        let num=parameter.CAMNUM.code;
 
        Generator.addImport(`import cv2\nimport numpy as np`)
        
        Generator.addCode(`cap = cv2.VideoCapture(${num})`)
        Generator.addCode(`cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)`)
        Generator.addImport(`import matplotlib.font_manager\nimport sys\nimport os`)
        Generator.addInit(`setwindowfull`,`if "linux" in sys.platform:
    font_path = 'HYQiHei_50S.ttf'
    cv2.namedWindow('cvwindow',cv2.WND_PROP_FULLSCREEN)
    cv2.setWindowProperty('cvwindow', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
else: 
    font_path = matplotlib.font_manager.findfont('SimHei')
`)
    Generator.addCode(`while not cap.isOpened():
    continue`)    
    }
         



    //% block="从摄像头当前帧获取图像 赋值给变量[IMG]" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    export function readcapcapture(parameter: any, block: any) {
        let img=parameter.IMG.code;
        Generator.addCode(`cv2.waitKey(5)\n${img}_success, ${img} = cap.read()`)

    }

            //% block="---"
            export function noteSep5() {

            }
        

    //% block="图像[IMG]旋转90度横屏" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    export function rotateImg(parameter: any, block: any) {
        let img=parameter.IMG.code;
        Generator.addCode(`${img} = cv2.rotate(${img}, cv2.ROTATE_90_COUNTERCLOCKWISE) `)

    }

    //% block="在图像[IMG]上绘制文字[TEXT] 颜色[COLOR] 坐标X[X]Y[Y] 字号[FSIZE]" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    //% TEXT.shadow="string" TEXT.defl="id1"
    //% COLOR.shadow="colorPalette" 
    //% X.shadow="number"   X.defl="10"
    //% Y.shadow="number"   Y.defl="20"
    //% FSIZE.shadow="number"   FSIZE.defl="40"
    export function drawText(parameter: any, block: any) {
        let img=parameter.IMG.code;
        let txt=parameter.TEXT.code;
        let color=parameter.COLOR.code;
        let x=parameter.X.code;
        let y=parameter.Y.code;
        let fsize=parameter.FSIZE.code;

        var r = 0;
        var g = 0;
        var b = 0;
        try {
            if ( color.length == 8 ) {//分别截取RGB值然后转换为数字值
                r = parseInt(color.substring(2, 4), 16);
                g = parseInt(color.substring(4, 6), 16);
                b = parseInt(color.substring(6, 8), 16);
            }
        } catch(e) {
            return '';
        }

        
        Generator.addImport(`from PIL import ImageFont, ImageDraw, Image`)
        

        Generator.addDeclaration("drawChineseFunction",`def drawChinese(text,x,y,size,r, g, b, a,img,font):
    font = ImageFont.truetype(font, size)
    img_pil = Image.fromarray(img)
    draw = ImageDraw.Draw(img_pil)
    draw.text((x,y), text, font=font, fill=(b, g, r, a))
    frame = np.array(img_pil)
    return frame
`)

    Generator.addCode(`${img} = drawChinese(text=str(${txt}),x=${x},y=${y},size=${fsize},r=${r},g=${g},b=${b},a=50,img=${img},font=font_path)`)     
    }

    

    //% block="将图像[IMG]显示到屏幕上" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    export function imShowVideo(parameter: any, block: any) {
        let img=parameter.IMG.code;
        Generator.addCode(`cv2.imshow('cvwindow', ${img})\ncv2.waitKey(2)`)
    }

    //% block="按钮[BUTTON]被按下?" blockType="boolean"
    //% BUTTON.shadow="string" BUTTON.defl="a"
    export function btPress(parameter: any, block: any) {
        let bt=parameter.BUTTON.code;
        Generator.addCode(`(cv2.waitKey(5) & 0xFF == ord(${bt}))`)
    }



    function replaceQuotationMarks(str:string){
            str=str.replace(/"/g, ""); //去除所有引号
            return str
    }


    
}
